package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
)

func main() {
	writeFile()
	//readFile()
	//bufReadFile()
}

func writeFile() {
	var file *os.File
	file, err := os.OpenFile("file.txt", os.O_CREATE | os.O_WRONLY, 0666)
	if err != nil {
		fmt.Println("file open err")
		return
	}
	defer file.Close()
	file.Seek(20,0)
	str := "this is write test\n"
	n, err := file.Write([]byte(str))
	//n, err := file.WriteAt([]byte(str), 100)
	if err != nil {
		fmt.Println(err)
		fmt.Println("file write err")
		return
	}
	fmt.Println("write"+ strconv.Itoa(n) +"个记录")
	file.WriteString("write string\n")

}



////普通读取
func readFile()  {
	var file *os.File
	file, err := os.Open("file.txt")
	if err != nil {
		fmt.Println("open error")
		return
	}
	defer file.Close()
	var content []byte
	var temp = make([]byte,128)
	for  {
		n, err := file.Read(temp)
		if err == io.EOF{
			fmt.Println("读取完了")
			break
		}
		if err != nil {
			fmt.Println("read error")
			return
		}
		content = append(content, temp[:n]...)
	}

	fmt.Println(string(content))
}
//缓存读取
func bufReadFile()  {
	var file *os.File
	file, err := os.Open("file.txt")
	if err != nil {
		fmt.Println("open error")
		return
	}
	defer file.Close()
	reader := bufio.NewReader(file)
	for {
		line, err := reader.ReadString('\n')
		if err == io.EOF {
			fmt.Println("读完了")
			break
		}
		if err != nil {
			fmt.Println("read error")
			return
		}
		fmt.Println(line)
	}
}
